// pages/search/search.js
Page({
    onShow() {
        //取出搜索记录
        wx.getStorage({
            key: 'search_record_arr',
            success: function (res) {
                this.setData({
                    search_record: res.data
                })
            }.bind(this)
        })
    },
    onLoad: function (options) {
        if (options.keyword) {
            this.setData({
                value: options.keyword
            })
        }
    },
    /**
     * 页面的初始数据
     */
    data: {
        focus: true,
        value: '',
        search_record: []
    },
    onSearch: function (e) {
        let keyword = e.detail;
        if (keyword){
            this.saveRecord(keyword)
        }
        wx.navigateTo({
            url: '/pages/room/room?keyword=' + keyword,
        })
    },
    searchRecord: function (e) {
        let keyword = e.target.dataset.record;
        this.setData({
            keyword: keyword
        })
        wx.navigateTo({
            url: '/pages/room/room?keyword=' + keyword,
        })
    },
    // 保存搜索记录
    saveRecord(val) {
        let isItRepeated = this.data.search_record.indexOf(val);
        // 这里是检测重复值
        if (isItRepeated !== -1) return;
        // 入队
        let len = this.data.search_record.push(val);
        // 出队
        if (len > 10) this.data.search_record.shift()
        wx.setStorage({
            key: 'search_record_arr',
            data: this.data.search_record,
        })
    },
    // 清除搜索记录（本地存储）
    clearRecord() {
        this.setData({
            search_record: []
        })
        wx.setStorage({
            key: 'search_record_arr',
            data: this.data.search_record,
        })
    },
    onCancel: function () {
        wx.navigateBack({ delta: 1 })
    }
})